package com.ljy.my_study.java.juc.Semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
* @author James
* @date 2018年9月10日 
*/
public class TestMain {
	public static void main(String[] args) {
		ExecutorService executorService= Executors.newCachedThreadPool();
		int count=10;
		final Semaphore semaphore=new Semaphore(count-8);
		for(int i=0;i<count;i++){
//			try {
//				Thread.sleep(100L);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			Runnable runnable=()->{
				try {
					semaphore.acquire();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("线程"+Thread.currentThread().getName()+"进入，已有"+(count-semaphore.availablePermits())
						+"个并发");
				try {
					Thread.sleep((long)(Math.random()*2000));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("线程"+Thread.currentThread().getName()+"离开，已有"+(count-semaphore.availablePermits())
						+"个并发");
				semaphore.release();
			};
			executorService.execute(runnable);
		}
//		try {
//			Thread.sleep(5000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
		try {
			semaphore.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println((count-semaphore.availablePermits())+"个并发");
		semaphore.release();
	}
}
